package access

import (
	"server/common"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

type ConnInfo struct {
	Conn       *websocket.Conn
	CreateTime time.Time
}

type ConnManager struct {
	conns map[string]ConnInfo // ConnId -> ConnInfo
	mtx   sync.RWMutex
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func NewConnManager() *ConnManager {
	return &ConnManager{
		conns: make(map[string]ConnInfo),
	}
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (cm *ConnManager) AddConn(connId string, conn *websocket.Conn) {
	common.Logger(common.SERVICE_TYPE_ACCESS).WithField("connId", connId).
		Info("adding new connection")

	cm.mtx.Lock()
	defer cm.mtx.Unlock()
	cm.conns[connId] = ConnInfo{
		Conn:       conn,
		CreateTime: time.Now(),
	}
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (cm *ConnManager) RemoveConn(connId string) {
	common.Logger(common.SERVICE_TYPE_ACCESS).WithField("connId", connId).
		Info("removing connection")

	cm.mtx.Lock()
	defer cm.mtx.Unlock()
	delete(cm.conns, connId)
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (cm *ConnManager) GetConn(connId string) (*websocket.Conn, bool) {
	cm.mtx.RLock()
	defer cm.mtx.RUnlock()
	connInfo, exists := cm.conns[connId]
	if !exists {
		return nil, false
	}
	return connInfo.Conn, true
}
